import { Index, Token } from "../../../dbserve";
import { rules } from '../../../utils/rules';
const addlist = {
  name: { required: true, type: String },//权限名称
  path: { required: true, type: String },// 路由 
  pid: { required: false, type: Number, default: "" },// 上级id
  code: { type: String }, // 菜单页面路由name，接口的唯一标识
  type: { required: true, type: Number },// 权限类型 1：标识菜单  2：标识接口路由
  icon: { required: false, type: String },//  菜单图标
  remarks: { required: false, type: String }, // 备注
}
const editlist = {
  ...addlist,
  id: { required: true }
}
export default class Role extends Index {
  constructor() { super('role'); this._getcoll() }
  // 添加权限
  async add(req?: any, res?: any) {
    try {
      const { data, message, error } = rules(req.body, addlist);
      if (error) throw message;
      const { name, path } = data;
      const num = await this._count({ $or: [{ name }, { path }] });
      if (num) throw '名称或地址已存在';
      const bool = await this._add(data);
      if (bool) res.success(bool, '添加成功');
      else throw '添加失败';
    } catch (error) {
      res.msg(error, 400);
    }
  }
  // 修改权限
  async edit(req?: any, res?: any) {
    try {
      const { data, message, error } = rules(req.body, editlist);
      if (error) throw message;
      const { name, path, id } = data;
      const num = await this._count({ id: { $ne: id }, $or: [{ name }, { path }] });
      if (num) throw '名称或地址已存在';
      const bool = await this._edit(data);
      if (bool) res.success(bool, '更新成功');
      else throw '更新失败';
    } catch (error) {
      res.msg(error, 400);
    }
  }
  // 删除权限
  async del(req?: any, res?: any) {
    try {
      let { id } = req.body;
      if (typeof id === 'number' && id) id = [id];
      if (!id || !id.length) throw '删除的数据id不能为空';
      let userinfo: any = await this._find({ id: { $in: id } });
      if (!userinfo.length) throw '目标不存在';
      const bool = await this._del(id);
      if (bool) res.success(bool, '删除成功');
      else throw '删除失败';
    } catch (error) {
      res.msg(error, 400);
    }
  }
  // 获取权限列表
  async list(req?: any, res?: any) {
    try {
      const { page = 1, size = 20, ...query } = req.query;
      const data = await this._query({ page: { page, size }, query });
      res.success(data)
    } catch (error) {
      res.msg(error, 400);
    }
  }
  async tree(req: any, res: any) {
    let { type } = req.query;
    let params = {};
    if (type) params = { type: type - 0 };
    const data = await this._find(params);
    const treeData = this.getTree("", data)
    res.success(treeData)
  }
  getTree(pid: any, items: Array<object | any>) {
    var _arr: Array<object> = [];
    items.forEach(item => {
      if (pid === item.pid) {
        item.children = this.getTree(item.id, items);
        _arr.push(item);
      }
    });
    return _arr;
  }
}



